import redis
from flask import current_app
from redis.exceptions import RedisError
from datetime import datetime


def get_redis_connection():
    try:
        return redis.Redis(
            host=current_app.config["REDIS_HOST"],
            port=current_app.config["REDIS_PORT"],
            db=current_app.config["REDIS_DB"],
            password=current_app.config["REDIS_PASSWORD"],
            decode_responses=True,
        )
    except RedisError as e:
        current_app.logger.error(f"Redis连接错误: {str(e)}")
        return None


def set_update_flag():
    """设置更新标志为1"""
    redis_conn = get_redis_connection()
    if redis_conn:
        try:
            redis_conn.set(current_app.config["REDIS_UPDATE_KEY"], "1")
            current_app.logger.info("更新标志已设置为1")
        except RedisError as e:
            current_app.logger.error(f"设置更新标志失败: {str(e)}")


def set_update_time():
    """设置算法完成运行的时间"""
    redis_conn = get_redis_connection()
    if redis_conn:
        try:
            current_time = datetime.now().isoformat()
            redis_conn.set("updatetime", current_time)
            current_app.logger.info(f"更新时间已设置: {current_time}")
        except RedisError as e:
            current_app.logger.error(f"设置更新时间失败: {str(e)}")


def get_update_time():
    """获取算法最后运行完成的时间"""
    redis_conn = get_redis_connection()
    if redis_conn:
        try:
            return redis_conn.get("updatetime")
        except RedisError as e:
            current_app.logger.error(f"获取更新时间失败: {str(e)}")
    return None
